package org.jcat.toolkit.mongodb;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;

import org.bson.Document;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import com.mongodb.Block;
import com.mongodb.client.FindIterable;

import static java.util.Arrays.asList;

import com.mongodb.client.AggregateIterable;



public class Main {
	
	
	public static void main(String[] args) throws ParseException {

		//获取连接
		MongoClient mongoClient = new MongoClient();
		MongoDatabase db = mongoClient.getDatabase("test");

		
		//插入数据
		System.out.println("\n===插入示例1：");
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
		db.getCollection("restaurants").insertOne(
		        new Document("address",
		                new Document()
		                        .append("street", "2 Avenue")
		                        .append("zipcode", "10075")
		                        .append("building", "1480")
		                        .append("coord", asList(-73.9557413, 40.7720266)))
		                .append("borough", "Manhattan")
		                .append("cuisine", "Italian")
		                .append("grades", asList(
		                        new Document()
		                                .append("date", format.parse("2014-10-01T00:00:00Z"))
		                                .append("grade", "A")
		                                .append("score", 11),
		                        new Document()
		                                .append("date", format.parse("2014-01-16T00:00:00Z"))
		                                .append("grade", "B")
		                                .append("score", 17)))
		                .append("name", "Vella")
		                .append("restaurant_id", "41704620"));
	
		
		
		//查询示例1	Query for All Documents in a Collection
		System.out.println("\n===>查询示例1：");
		FindIterable<Document> iterable = db.getCollection("restaurants").find();
		iterable.forEach(new Block<Document>() {
		    @Override
		    public void apply(final Document document) {
		        System.out.println(document);
		    }
		});
		
		//查询示例2	Query by a Top Level Field
		System.out.println("\n===>查询示例2：");
		FindIterable<Document> iterable2 = db.getCollection("restaurants").find(
		        new Document("name", "Vella"));
		//使用静态方法
		//db.getCollection("restaurants").find(eq("borough", "Manhattan"));
		
		iterable2.forEach(new Block<Document>() {
		    @Override
		    public void apply(final Document document) {
		        System.out.println(document);
		    }
		});
		
		
		//查询示例3	Query by a Field in an Embedded Document
		System.out.println("\n===>查询示例3：");
		FindIterable<Document> iterable3 = db.getCollection("restaurants").find(
		        new Document("address.zipcode", "10075"));
		//使用静态方法
		//db.getCollection("restaurants").find(eq("address.zipcode", "10075"));
		iterable3.forEach(new Block<Document>() {
		    @Override
		    public void apply(final Document document) {
		        System.out.println(document);
		    }
		});
		
		
		
		//查询示例4	Query by a Field in an Array
		System.out.println("\n===>查询示例4：");
		FindIterable<Document> iterable4 = db.getCollection("restaurants").find(
		        new Document("grades.grade", "B"));
		//使用静态方法
		//db.getCollection("restaurants").find(eq("grades.grade", "B"));
		
		iterable4.forEach(new Block<Document>() {
		    @Override
		    public void apply(final Document document) {
		        System.out.println(document);
		    }
		});
		
		
		
		//查询示例5	Greater Than Operator ($gt)
		System.out.println("\n===>查询示例5：");
		FindIterable<Document> iterable5 = db.getCollection("restaurants").find(
		        new Document("grades.score", new Document("$gt", 30)));
		//使用静态方法
		//db.getCollection("restaurants").find(gt("grades.score", 30));
		
		iterable5.forEach(new Block<Document>() {
		    @Override
		    public void apply(final Document document) {
		        System.out.println(document);
		    }
		});
		
		
		//查询示例6	Less Than Operator ($lt)
		System.out.println("\n===>查询示例6：");
		FindIterable<Document> iterable6 = db.getCollection("restaurants").find(
		        new Document("grades.score", new Document("$lt", 10)));
		//使用静态方法
		//db.getCollection("restaurants").find(lt("grades.score", 10));
		
		iterable6.forEach(new Block<Document>() {
		    @Override
		    public void apply(final Document document) {
		        System.out.println(document);
		    }
		});
		
		
		
		//查询示例7	Logical AND
		System.out.println("\n===>查询示例7：");
		FindIterable<Document> iterable7 = db.getCollection("restaurants").find(
		        new Document("cuisine", "Italian").append("address.zipcode", "10075"));
		//Using the static Filters helper(s), you can also specify the query as follows:
		//db.getCollection("restaurants").find(and(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
		
		iterable7.forEach(new Block<Document>() {
		    @Override
		    public void apply(final Document document) {
		        System.out.println(document);
		    }
		});
		
		
		
		//查询示例8	Logical OR
		System.out.println("\n===>查询示例8：");
		FindIterable<Document> iterable8 = db.getCollection("restaurants").find(
		        new Document("$or", asList(new Document("cuisine", "Italian"),
		                new Document("address.zipcode", "10075"))));
		
		//Using the static Filters helper(s), you can also specify the query as follows:
		//db.getCollection("restaurants").find(or(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
		
		iterable8.forEach(new Block<Document>() {
		    @Override
		    public void apply(final Document document) {
		        System.out.println(document);
		    }
		});
		
		
		
		//查询示例9	Sort Query Results
		System.out.println("\n===>查询示例9：");
		FindIterable<Document> iterable9 = db.getCollection("restaurants").find()
		        .sort(new Document("borough", 1).append("address.zipcode", 1));
		
		//Using the static Sorts helper(s), you can also specify the query as follows:
		//db.getCollection("restaurants").find().sort(ascending("borough", "address.zipcode"));
		
		iterable9.forEach(new Block<Document>() {
		    @Override
		    public void apply(final Document document) {
		        System.out.println(document);
		    }
		});
		
		
		//查询示例10	Group Documents by a Field and Calculate Count
		System.out.println("\n===>查询示例10：");
		AggregateIterable<Document> iterable10 = db.getCollection("restaurants").aggregate(asList(
		        new Document("$group", new Document("_id", "$borough").append("count", new Document("$sum", 1)))));
		iterable.forEach(new Block<Document>() {
		    @Override
		    public void apply(final Document document) {
		        System.out.println(document.toJson());
		    }
		});
		
		
		
		//查询示例11	Filter and Group Documents
		System.out.println("\n===>查询示例11：");
		AggregateIterable<Document> iterable11 = db.getCollection("restaurants").aggregate(asList(
		        new Document("$match", new Document("borough", "Queens").append("cuisine", "Brazilian")),
		        new Document("$group", new Document("_id", "$address.zipcode").append("count", new Document("$sum", 1)))));
		iterable11.forEach(new Block<Document>() {
		    @Override
		    public void apply(final Document document) {
		        System.out.println(document.toJson());
		    }
		});
		
		
		
		//更新示例1	Update Top-Level Fields
		System.out.println("\n===>更新示例1：");
		db.getCollection("restaurants").updateOne(new Document("name", "Juni"),
		        new Document("$set", new Document("cuisine", "American (New)"))
		            .append("$currentDate", new Document("lastModified", true)));
		
		
		//更新示例2	Update an Embedded Field
		System.out.println("\n===>更新示例2：");
		db.getCollection("restaurants").updateOne(new Document("restaurant_id", "41156888"),
		        new Document("$set", new Document("address.street", "East 31st Street")));
		
		//更新示例3
		System.out.println("\n===>更新示例3：");
		db.getCollection("restaurants").updateMany(new Document("address.zipcode", "10016").append("cuisine", "Other"),
		        new Document("$set", new Document("cuisine", "Category To Be Determined"))
		                .append("$currentDate", new Document("lastModified", true)));
		
		
		
		//更新示例4
		System.out.println("\n===>更新示例4：");
		db.getCollection("restaurants").replaceOne(new Document("restaurant_id", "41156888"),
		        new Document("address",
		                new Document()
		                        .append("street", "2 Avenue")
		                        .append("zipcode", "10075")
		                        .append("building", "1480")
		                        .append("coord", asList(-73.9557413, 40.7720266)))
		                .append("name", "Vella 2"));
		
		
		
		//删除示例1	Remove All Documents That Match a Condition
		System.out.println("\n===>删除示例1：");
		db.getCollection("restaurants").deleteMany(new Document("borough", "Manhattan"));
		
		//删除示例2	Remove All Documents
		System.out.println("\n===>删除示例2：");
		db.getCollection("restaurants").deleteMany(new Document());
		
		
		//删除示例3	Drop a Collection
		System.out.println("\n===>删除示例3：");
		db.getCollection("restaurants").drop();
		
		
		//创建索引1	Create a Single-Field Index
		System.out.println("\n===>创建索引示例1：");
		db.getCollection("restaurants").createIndex(new Document("cuisine", 1));

		//创建索引2	Create a compound index
		System.out.println("\n===>创建索引示例2：");
		db.getCollection("restaurants").createIndex(new Document("cuisine", 1).append("address.zipcode", -1));
	}
	
	
	
}
